import { OnMessageCallback } from 'mqtt';
import connect from './connect';

/**
 * on
 * @param url mqtt连接地址
 * @param topic 主题
 * @param cb 回调函数
 */
export default async function on(url: string, topic: string, cb: OnMessageCallback) {
	const client = await connect(url);
	client.subscribe(topic);
	client.on('message', cb);
	return {
		destroy() {
			client.unsubscribe(topic);
			client.removeListener('message', cb);
			client.end();
		}
	};
}
